#!/bin/bash
# ============================================
# 安全配置验证脚本
# Security Configuration Verification Script
# ============================================
# 脚本名称：verify-security.sh
# 脚本作者：System Administrator
# 脚本版本：1.0
# 创建日期：2024
# 脚本用途：验证系统安全配置是否正确应用
# 功能说明：
#   - 检查SSH服务安全配置
#   - 验证防火墙规则和状态
#   - 检查用户账户安全设置
#   - 验证文件权限和所有权
#   - 检查系统服务安全配置
#   - 验证日志和审计配置
# 使用方法：sudo ./verify-security.sh
# ============================================

# ============================================
# 输出颜色定义
# 用于美化脚本输出，提高可读性
# ============================================
RED='\033[0;31m'     # 红色 - 用于失败状态和错误信息
GREEN='\033[0;32m'   # 绿色 - 用于成功状态和正常信息
YELLOW='\033[1;33m'  # 黄色 - 用于警告状态和注意事项
BLUE='\033[0;34m'    # 蓝色 - 用于信息状态和标题显示
NC='\033[0m'         # 无颜色 - 重置颜色到默认状态

# ============================================
# 检查计数器
# 用于统计验证结果和生成报告
# ============================================
TOTAL_CHECKS=0       # 总检查项数 - 记录执行的所有检查
PASSED_CHECKS=0      # 通过检查项数 - 记录成功通过的检查
FAILED_CHECKS=0      # 失败检查项数 - 记录失败的检查
WARNING_CHECKS=0     # 警告检查项数 - 记录需要注意的检查

# ============================================
# 彩色输出结果函数
# 功能：格式化输出检查结果并更新统计计数器
# 参数：
#   $1 - 检查状态 (PASS/FAIL/WARN/INFO)
#   $2 - 消息内容
#   $3 - 详细说明 (可选)
# 用途：统一管理所有检查结果的输出格式
# ============================================
print_result() {
    local status="$1"    # 检查状态：PASS/FAIL/WARN/INFO
    local message="$2"   # 主要输出消息内容
    local detail="$3"    # 详细说明信息（可选）
    
    # 增加总检查计数（INFO状态不计入总数）
    if [ "$status" != "INFO" ]; then
        TOTAL_CHECKS=$((TOTAL_CHECKS + 1))
    fi
    
    # 根据状态类型进行彩色输出和计数更新
    case "$status" in
        "PASS")
            echo -e "${GREEN}[PASS]${NC} $message"  # 绿色显示通过状态
            PASSED_CHECKS=$((PASSED_CHECKS + 1))
            [ -n "$detail" ] && echo -e "       ${GREEN}→${NC} $detail"
            ;;
        "FAIL")
            echo -e "${RED}[FAIL]${NC} $message"   # 红色显示失败状态
            FAILED_CHECKS=$((FAILED_CHECKS + 1))
            [ -n "$detail" ] && echo -e "       ${RED}→${NC} $detail"
            ;;
        "WARN")
            echo -e "${YELLOW}[WARN]${NC} $message" # 黄色显示警告状态
            WARNING_CHECKS=$((WARNING_CHECKS + 1))
            [ -n "$detail" ] && echo -e "       ${YELLOW}→${NC} $detail"
            ;;
        "INFO")
            echo -e "${BLUE}[INFO]${NC} $message"  # 蓝色显示信息状态
            [ -n "$detail" ] && echo -e "       ${BLUE}→${NC} $detail"
            ;;
    esac
}

# ============================================
# SSH配置检查函数
# Function to check SSH security configuration
# ============================================
# 功能说明 (Function description):
#   验证SSH服务的安全配置项，确保SSH服务符合安全最佳实践
#   Verifies SSH service security configuration to ensure SSH service follows security best practices
# 检查项目 (Check items):
#   - SSH配置文件存在性和可读性 (SSH config file existence and readability)
#   - SSH端口配置（建议非默认端口22） (SSH port configuration, recommend non-default port)
#   - Root用户登录权限控制 (Root user login permission control)
#   - 密码认证和公钥认证设置 (Password and public key authentication settings)
#   - SSH协议版本安全性 (SSH protocol version security)
#   - 最大认证尝试次数限制 (Maximum authentication attempts limit)
#   - SSH服务运行状态 (SSH service running status)
#   - SSH配置文件语法正确性 (SSH config file syntax correctness)
# 安全建议 (Security recommendations):
#   - 使用非默认端口减少扫描攻击 (Use non-default port to reduce scan attacks)
#   - 禁用root直接登录 (Disable direct root login)
#   - 使用密钥认证替代密码认证 (Use key authentication instead of password)
#   - 限制认证尝试次数防止暴力破解 (Limit auth attempts to prevent brute force)
# ============================================
check_ssh_config() {
    echo -e "\n${BLUE}=== SSH安全配置检查 ===${NC}"
    
    local sshd_config="/etc/ssh/sshd_config"  # SSH主配置文件路径 (SSH main config file path)
    
    # 检查SSH配置文件是否存在
    if [ ! -f "$sshd_config" ]; then
        print_result "FAIL" "SSH配置文件未找到" "配置文件路径: $sshd_config"
        return
    fi
    
    print_result "PASS" "SSH配置文件存在" "配置文件: $sshd_config"
    
    # 检查SSH端口配置（建议使用非默认端口）
    local ssh_port=$(grep "^Port" "$sshd_config" | awk '{print $2}' || echo "22")
    if [ "$ssh_port" != "22" ]; then
        print_result "PASS" "SSH端口已修改为非默认端口" "当前端口: $ssh_port"
    else
        print_result "WARN" "SSH仍使用默认端口22" "建议修改为其他端口以提高安全性"
    fi
    
    # 检查root用户登录权限（应该被限制或禁用）
    local root_login=$(grep "^PermitRootLogin" "$sshd_config" | awk '{print $2}' || echo "yes")
    if [ "$root_login" = "no" ]; then
        print_result "PASS" "Root用户登录已禁用" "配置: PermitRootLogin $root_login"
    elif [ "$root_login" = "without-password" ] || [ "$root_login" = "prohibit-password" ]; then
        print_result "PASS" "Root用户仅允许密钥登录" "配置: PermitRootLogin $root_login"
    else
        print_result "FAIL" "Root用户登录权限过于宽松" "当前配置: $root_login，建议设置为no或without-password"
    fi
    
    # 检查密码认证设置（建议禁用，使用密钥认证）
    local password_auth=$(grep "^PasswordAuthentication" "$sshd_config" | awk '{print $2}' || echo "yes")
    if [ "$password_auth" = "no" ]; then
        print_result "PASS" "密码认证已禁用" "使用密钥认证更安全"
    else
        print_result "WARN" "密码认证已启用" "建议禁用密码认证，使用SSH密钥"
    fi
    
    # 检查公钥认证设置（应该启用）
    local pubkey_auth=$(grep "^PubkeyAuthentication" "$sshd_config" | awk '{print $2}' || echo "yes")
    if [ "$pubkey_auth" = "yes" ]; then
        print_result "PASS" "公钥认证已启用" "推荐的安全认证方式"
    else
        print_result "WARN" "公钥认证已禁用" "建议启用公钥认证以提高安全性"
    fi
    
    # 检查最大认证尝试次数（防止暴力破解）
    local max_auth_tries=$(grep "^MaxAuthTries" "$sshd_config" | awk '{print $2}' || echo "6")
    if [ "$max_auth_tries" -le 3 ]; then
        print_result "PASS" "最大认证尝试次数已限制" "当前设置: $max_auth_tries 次"
    else
        print_result "WARN" "最大认证尝试次数较高" "当前: $max_auth_tries 次，建议设置为3次或更少"
    fi
    
    # 检查SSH协议版本（应该使用版本2）
    local protocol_version=$(grep "^Protocol" "$sshd_config" | awk '{print $2}' || echo "2")
    if [ "$protocol_version" = "2" ]; then
        print_result "PASS" "SSH协议版本2已启用" "安全的协议版本"
    else
        print_result "FAIL" "SSH协议版本不安全" "当前版本: $protocol_version，应使用版本2"
    fi
    
    # 检查SSH服务运行状态
    if systemctl is-active --quiet sshd || systemctl is-active --quiet ssh; then
        print_result "PASS" "SSH服务正在运行" "服务状态正常"
    else
        print_result "FAIL" "SSH服务未运行" "请启动SSH服务"
    fi
    
    # 测试SSH配置文件语法正确性
    if sshd -t 2>/dev/null; then
        print_result "PASS" "SSH配置文件语法正确" "配置文件格式有效"
    else
        print_result "FAIL" "SSH配置文件存在语法错误" "请检查配置文件语法"
    fi
}

# ============================================
# 防火墙配置检查函数
# Function to check firewall configuration
# ============================================
# 功能说明 (Function description):
#   检查系统防火墙的配置和状态，确保网络安全防护措施到位
#   Check system firewall configuration and status to ensure network security protection is in place
# 检查项目 (Check items):
#   - UFW防火墙状态和默认策略 (UFW firewall status and default policies)
#   - Firewalld防火墙状态和区域配置 (Firewalld status and zone configuration)
#   - iptables规则配置情况 (iptables rules configuration)
#   - 防火墙服务运行状态 (Firewall service running status)
#   - 网络端口开放情况 (Network port opening status)
# 支持的防火墙类型 (Supported firewall types):
#   - UFW (Uncomplicated Firewall) - Ubuntu/Debian系统
#   - Firewalld - RHEL/CentOS/Fedora系统
#   - iptables - 传统Linux防火墙
# 安全建议 (Security recommendations):
#   - 启用防火墙保护系统 (Enable firewall to protect system)
#   - 设置入站连接默认拒绝策略 (Set default deny policy for incoming connections)
#   - 仅开放必要的服务端口 (Only open necessary service ports)
#   - 定期审查防火墙规则 (Regularly review firewall rules)
# ============================================
check_firewall_config() {
    echo -e "\n${BLUE}=== 防火墙配置检查 ===${NC}"
    
    # 初始化防火墙状态标志 (Initialize firewall status flag)
    local firewall_active=false
    
    # 检查UFW防火墙状态 (Ubuntu/Debian系统)
    if command -v ufw >/dev/null 2>&1; then
        if ufw status | grep -q "Status: active"; then
            print_result "PASS" "UFW防火墙已激活" "防火墙正在保护系统"
            firewall_active=true
            
            # 检查UFW默认策略配置
            local incoming=$(ufw status verbose | grep "Default:" | grep "incoming" | awk '{print $2}')
            local outgoing=$(ufw status verbose | grep "Default:" | grep "outgoing" | awk '{print $2}')
            
            # 检查入站连接默认策略（应该拒绝）
            if [ "$incoming" = "deny" ]; then
                print_result "PASS" "入站连接默认拒绝" "安全的默认策略"
            else
                print_result "WARN" "入站连接策略不安全" "当前策略: $incoming，建议设置为deny"
            fi
            
            # 检查出站连接默认策略
            if [ "$outgoing" = "allow" ]; then
                print_result "PASS" "出站连接默认允许" "正常的网络访问策略"
            else
                print_result "INFO" "出站连接策略" "当前策略: $outgoing"
            fi
        else
            print_result "FAIL" "UFW防火墙未激活" "请启用UFW防火墙保护系统"
        fi
    fi
    
    # 检查firewalld防火墙状态 (RHEL/CentOS系统)
    if command -v firewall-cmd >/dev/null 2>&1; then
        if firewall-cmd --state >/dev/null 2>&1; then
            print_result "PASS" "Firewalld防火墙正在运行" "RHEL/CentOS系统防火墙已启用"
            firewall_active=true
            
            # 检查默认防火墙区域配置
            local default_zone=$(firewall-cmd --get-default-zone 2>/dev/null)
            print_result "INFO" "默认防火墙区域" "当前区域: $default_zone"
            
            # 检查活动防火墙区域
            local active_zones=$(firewall-cmd --get-active-zones 2>/dev/null | grep -v "interfaces:")
            print_result "INFO" "活动防火墙区域" "当前活动区域: $active_zones"
            
            # 检查防火墙服务状态
            local enabled_services=$(firewall-cmd --list-services 2>/dev/null)
            print_result "INFO" "已启用的服务" "服务列表: $enabled_services"
        else
            print_result "FAIL" "Firewalld防火墙未运行" "请启动firewalld服务"
        fi
    fi
    
    # 检查iptables规则配置
    if command -v iptables >/dev/null 2>&1; then
        local iptables_rules=$(iptables -L | wc -l)
        if [ $iptables_rules -gt 10 ]; then
            print_result "PASS" "iptables规则已配置" "规则数量: $iptables_rules 行"
        else
            print_result "WARN" "iptables规则较少" "当前规则: $iptables_rules 行，可能需要更多安全规则"
        fi
        
        # 检查iptables是否阻止ping（可选安全措施）
        if iptables -L | grep -q "ICMP"; then
            print_result "INFO" "ICMP规则已配置" "已设置ping相关规则"
        fi
    fi
    
    # 检查是否有任何防火墙处于活动状态
    if [ "$firewall_active" = false ]; then
        print_result "FAIL" "未检测到活动防火墙" "系统缺乏防火墙保护，存在安全风险"
    fi
}

# ============================================
# SELinux配置检查函数
# Function to check SELinux security module configuration
# ============================================
# 功能说明 (Function description):
#   检查SELinux安全增强模块的配置状态，确保强制访问控制正常工作
#   Check SELinux security enhancement module configuration to ensure mandatory access control works properly
# 检查项目 (Check items):
#   - SELinux运行模式状态 (SELinux running mode status: Enforcing/Permissive/Disabled)
#   - SELinux策略类型配置 (SELinux policy type configuration)
#   - SELinux访问拒绝记录 (SELinux access denial records)
#   - SELinux布尔值设置 (SELinux boolean settings)
#   - SELinux配置文件检查 (SELinux configuration file check)
# SELinux模式说明 (SELinux mode description):
#   - Enforcing: 强制模式，严格执行安全策略 (Enforcing mode, strictly enforce security policies)
#   - Permissive: 宽容模式，记录违规但不阻止 (Permissive mode, log violations but don't block)
#   - Disabled: 禁用模式，无强制访问控制 (Disabled mode, no mandatory access control)
# 安全建议 (Security recommendations):
#   - 生产环境建议使用Enforcing模式 (Use Enforcing mode in production environment)
#   - 定期检查SELinux拒绝日志 (Regularly check SELinux denial logs)
#   - 根据需要调整SELinux布尔值 (Adjust SELinux booleans as needed)
# ============================================
check_selinux_config() {
    echo -e "\n${BLUE}=== SELinux安全模块检查 ===${NC}"
    
    # 检查系统是否支持SELinux (Check if system supports SELinux)
    if command -v getenforce >/dev/null 2>&1; then
        # 获取SELinux当前运行状态 (Get current SELinux running status)
        local selinux_status=$(getenforce 2>/dev/null)
        case "$selinux_status" in
            "Enforcing")
                print_result "PASS" "SELinux强制模式已启用" "最高安全级别，强制执行安全策略"
                ;;
            "Permissive")
                print_result "WARN" "SELinux宽容模式" "记录违规但不阻止，建议切换到强制模式"
                ;;
            "Disabled")
                print_result "FAIL" "SELinux已禁用" "缺乏强制访问控制，存在安全风险"
                ;;
            *)
                print_result "WARN" "SELinux状态未知" "当前状态: $selinux_status"
                ;;
        esac
        
        # 检查SELinux策略类型配置
        if [ -f "/etc/selinux/config" ]; then
            local selinux_policy=$(grep "^SELINUXTYPE=" /etc/selinux/config | cut -d'=' -f2)
            if [ "$selinux_policy" = "targeted" ]; then
                print_result "PASS" "SELinux策略类型" "使用targeted策略（推荐）"
            else
                print_result "INFO" "SELinux策略类型" "当前策略: $selinux_policy"
            fi
        fi
        
        # 检查SELinux访问拒绝记录
        if command -v ausearch >/dev/null 2>&1; then
            local denials=$(ausearch -m avc -ts recent 2>/dev/null | wc -l)
            if [ $denials -eq 0 ]; then
                print_result "PASS" "无SELinux拒绝记录" "近期无访问违规行为"
            else
                print_result "WARN" "发现SELinux拒绝记录" "近期有 $denials 条访问被拒绝，请检查日志"
            fi
        fi
        
        # 检查SELinux布尔值设置
        if command -v getsebool >/dev/null 2>&1; then
            local httpd_can_network=$(getsebool httpd_can_network_connect 2>/dev/null | awk '{print $3}')
            if [ "$httpd_can_network" = "on" ]; then
                print_result "INFO" "HTTP网络连接" "httpd_can_network_connect已启用"
            fi
        fi
    else
        print_result "INFO" "SELinux不可用" "当前系统不支持SELinux"
    fi
}

# ============================================
# 审计配置检查函数
# Function to check system audit configuration
# ============================================
# 功能说明 (Function description):
#   检查系统审计服务的配置和运行状态，确保系统活动被正确记录和监控
#   Check system audit service configuration and running status to ensure system activities are properly logged and monitored
# 检查项目 (Check items):
#   - auditd审计守护进程运行状态 (auditd audit daemon running status)
#   - 审计规则配置情况 (audit rules configuration)
#   - 审计日志文件存在性和大小 (audit log files existence and size)
#   - 关键系统调用审计规则 (critical system call audit rules)
#   - 审计配置文件检查 (audit configuration file check)
# 审计重要性 (Audit importance):
#   - 合规性要求：满足安全标准和法规 (Compliance requirements: meet security standards and regulations)
#   - 安全监控：检测异常和恶意活动 (Security monitoring: detect anomalies and malicious activities)
#   - 事件追踪：提供详细的系统活动记录 (Event tracking: provide detailed system activity records)
#   - 取证分析：支持安全事件调查 (Forensic analysis: support security incident investigation)
# 关键审计规则 (Key audit rules):
#   - execve: 监控进程执行 (Monitor process execution)
#   - file access: 监控文件访问 (Monitor file access)
#   - network: 监控网络活动 (Monitor network activities)
# ============================================
check_audit_config() {
    echo -e "\n${BLUE}=== 系统审计配置检查 ===${NC}"
    
    # 检查auditd审计守护进程状态 (Check auditd audit daemon status)
    if systemctl is-active --quiet auditd; then
        print_result "PASS" "审计服务正在运行" "auditd守护进程已启动"
    else
        print_result "FAIL" "审计服务未运行" "请启动auditd服务以记录系统活动"
    fi
    
    # 检查审计规则配置情况
    if command -v auditctl >/dev/null 2>&1; then
        local audit_rules=$(auditctl -l 2>/dev/null | wc -l)
        if [ $audit_rules -gt 0 ]; then
            print_result "PASS" "审计规则已配置" "当前规则数量: $audit_rules 条"
        else
            print_result "WARN" "未配置审计规则" "建议配置审计规则以监控系统活动"
        fi
        
        # 检查关键系统调用的审计规则
        if auditctl -l 2>/dev/null | grep -q "execve"; then
            print_result "PASS" "进程执行审计已启用" "监控execve系统调用"
        else
            print_result "WARN" "缺少进程执行审计" "建议添加execve审计规则"
        fi
    fi
    
    # 检查审计日志文件存在性
    if [ -d "/var/log/audit" ]; then
        local audit_logs=$(find /var/log/audit -name "audit.log*" | wc -l)
        if [ $audit_logs -gt 0 ]; then
            print_result "PASS" "审计日志文件存在" "发现 $audit_logs 个日志文件"
            
            # 检查最新日志文件的大小
            local latest_log_size=$(ls -lh /var/log/audit/audit.log 2>/dev/null | awk '{print $5}' || echo "unknown")
            print_result "INFO" "当前日志文件大小" "audit.log: $latest_log_size"
        else
            print_result "WARN" "未找到审计日志文件" "可能审计服务未正常工作"
        fi
    else
        print_result "WARN" "审计日志目录不存在" "审计功能可能未安装或配置"
    fi
    
    # 检查审计配置文件
    if [ -f "/etc/audit/auditd.conf" ]; then
        print_result "PASS" "审计配置文件存在" "配置文件: /etc/audit/auditd.conf"
        
        # 检查日志文件大小限制设置
        local max_log_file=$(grep "^max_log_file" /etc/audit/auditd.conf | awk '{print $3}' || echo "unknown")
        print_result "INFO" "最大日志文件大小" "限制: $max_log_file MB"
        
        # 检查日志轮转动作
        local max_log_file_action=$(grep "^max_log_file_action" /etc/audit/auditd.conf | awk '{print $3}' || echo "unknown")
        print_result "INFO" "日志文件满时动作" "动作: $max_log_file_action"
    else
        print_result "WARN" "审计配置文件不存在" "请安装并配置auditd"
    fi
}

# ============================================
# Fail2Ban入侵防护检查函数
# Function to check Fail2Ban intrusion protection system
# ============================================
# 功能说明 (Function description):
#   检查Fail2Ban入侵防护系统的配置和状态，确保系统能够自动防护暴力破解攻击
#   Check Fail2Ban intrusion protection system configuration and status to ensure automatic protection against brute force attacks
# 检查项目 (Check items):
#   - Fail2Ban服务运行状态 (Fail2Ban service running status)
#   - 活动监狱（jail）配置情况 (Active jail configuration)
#   - 被封禁的IP地址统计 (Banned IP addresses statistics)
#   - 配置文件存在性检查 (Configuration files existence check)
#   - 监狱规则有效性验证 (Jail rules effectiveness validation)
# Fail2Ban工作原理 (Fail2Ban working principle):
#   - 监控日志文件检测异常行为 (Monitor log files to detect abnormal behavior)
#   - 根据规则自动封禁恶意IP (Automatically ban malicious IPs based on rules)
#   - 支持多种服务防护（SSH、HTTP等） (Support protection for multiple services like SSH, HTTP)
#   - 可配置封禁时间和重试次数 (Configurable ban time and retry attempts)
# 监狱类型 (Jail types):
#   - sshd: SSH服务防护 (SSH service protection)
#   - apache: Apache web服务防护 (Apache web service protection)
#   - nginx: Nginx web服务防护 (Nginx web service protection)
#   - postfix: 邮件服务防护 (Mail service protection)
# 安全建议 (Security recommendations):
#   - 启用SSH监狱防护暴力破解 (Enable SSH jail to protect against brute force)
#   - 定期检查被封禁IP列表 (Regularly check banned IP list)
#   - 根据服务需求配置相应监狱 (Configure appropriate jails based on service requirements)
# ============================================
check_fail2ban_config() {
    echo -e "\n${BLUE}=== Fail2Ban入侵防护检查 ===${NC}"
    
    # 检查Fail2Ban是否已安装 (Check if Fail2Ban is installed)
    if command -v fail2ban-client >/dev/null 2>&1; then
        # 检查Fail2Ban服务运行状态
        if systemctl is-active --quiet fail2ban; then
            print_result "PASS" "Fail2Ban服务正在运行" "入侵防护系统已启动"
            
            # 检查活动监狱数量
            local active_jails=$(fail2ban-client status 2>/dev/null | grep "Jail list:" | cut -d':' -f2 | tr ',' '\n' | wc -w)
            if [ $active_jails -gt 0 ]; then
                print_result "PASS" "Fail2Ban监狱已配置" "当前活动监狱: $active_jails 个"
                
                # 列出活动监狱名称
                local jails=$(fail2ban-client status 2>/dev/null | grep "Jail list:" | cut -d':' -f2 | tr -d ' ')
                print_result "INFO" "活动监狱列表" "监狱: $jails"
            else
                print_result "WARN" "无活动Fail2Ban监狱" "建议配置SSH等服务的防护监狱"
            fi
            
            # 统计被封禁的IP地址总数
            local banned_ips=0
            for jail in $(fail2ban-client status 2>/dev/null | grep "Jail list:" | cut -d':' -f2 | tr ',' ' '); do
                local jail_banned=$(fail2ban-client status "$jail" 2>/dev/null | grep "Currently banned:" | awk '{print $3}' || echo "0")
                banned_ips=$((banned_ips + jail_banned))
            done
            
            # 显示被封禁IP统计信息
            if [ $banned_ips -gt 0 ]; then
                print_result "INFO" "当前被封禁IP数量" "已封禁: $banned_ips 个IP地址"
            else
                print_result "INFO" "当前无被封禁IP" "系统暂无检测到恶意IP"
            fi
        else
            print_result "FAIL" "Fail2Ban服务未运行" "请启动fail2ban服务"
        fi
        
        # 检查配置文件存在性
        if [ -f "/etc/fail2ban/jail.local" ]; then
            print_result "PASS" "Fail2Ban本地配置存在" "配置文件: /etc/fail2ban/jail.local"
        else
            print_result "WARN" "未找到Fail2Ban本地配置" "建议创建jail.local文件进行自定义配置"
        fi
        
        # 检查默认配置文件
        if [ -f "/etc/fail2ban/jail.conf" ]; then
            print_result "INFO" "Fail2Ban默认配置存在" "配置文件: /etc/fail2ban/jail.conf"
        fi
    else
        print_result "WARN" "Fail2Ban未安装" "建议安装fail2ban以防护暴力破解攻击"
    fi
}

# ============================================
# 密码策略检查函数
# Function to check system password policy
# ============================================
# 功能说明 (Function description):
#   检查系统密码策略的配置和强度要求，确保用户密码符合安全标准
#   Check system password policy configuration and strength requirements to ensure user passwords meet security standards
# 检查项目 (Check items):
#   - 密码质量配置文件检查 (Password quality configuration file check)
#   - PAM密码模块配置验证 (PAM password module configuration verification)
#   - 密码长度和复杂度要求 (Password length and complexity requirements)
#   - 字符类别要求设置 (Character category requirements)
#   - 密码历史和重用策略 (Password history and reuse policy)
# 密码安全标准 (Password security standards):
#   - 最小长度：建议12位以上 (Minimum length: recommend 12+ characters)
#   - 字符类别：大小写字母、数字、特殊字符 (Character types: uppercase, lowercase, digits, special chars)
#   - 复杂度要求：避免简单模式 (Complexity requirements: avoid simple patterns)
#   - 历史限制：防止密码重用 (History restriction: prevent password reuse)
# PAM模块说明 (PAM module description):
#   - pam_pwquality.so: 密码质量检查模块 (Password quality check module)
#   - pam_unix.so: Unix密码认证模块 (Unix password authentication module)
#   - pam_cracklib.so: 密码强度检查模块（旧版） (Password strength check module - legacy)
# 配置文件位置 (Configuration file locations):
#   - /etc/security/pwquality.conf: 密码质量配置 (Password quality configuration)
#   - /etc/pam.d/common-password: Debian/Ubuntu PAM配置 (Debian/Ubuntu PAM config)
#   - /etc/pam.d/system-auth: RHEL/CentOS PAM配置 (RHEL/CentOS PAM config)
# ============================================
check_password_policy() {
    echo -e "\n${BLUE}=== 密码策略检查 ===${NC}"
    
    # 检查密码质量配置文件 (Check password quality configuration file)
    if [ -f "/etc/security/pwquality.conf" ]; then
        print_result "PASS" "密码质量配置文件存在" "配置文件: /etc/security/pwquality.conf"
        
        # 检查最小密码长度要求
        local minlen=$(grep "^minlen" /etc/security/pwquality.conf | awk '{print $3}' || echo "unknown")
        if [ "$minlen" != "unknown" ] && [ $minlen -ge 12 ]; then
            print_result "PASS" "密码最小长度符合要求" "当前要求: $minlen 位（推荐12位以上）"
        else
            print_result "WARN" "密码长度要求较低" "当前: $minlen 位，建议设置为12位以上"
        fi
        
        # 检查字符类别要求
        local minclass=$(grep "^minclass" /etc/security/pwquality.conf | awk '{print $3}' || echo "unknown")
        if [ "$minclass" != "unknown" ] && [ $minclass -ge 3 ]; then
            print_result "PASS" "字符类别要求合理" "要求包含: $minclass 种字符类型"
        else
            print_result "WARN" "字符类别要求不足" "当前: $minclass 种，建议要求3种以上（大小写字母、数字、特殊字符）"
        fi
        
        # 检查密码复杂度要求
        local dcredit=$(grep "^dcredit" /etc/security/pwquality.conf | awk '{print $3}' || echo "unknown")
        if [ "$dcredit" != "unknown" ]; then
            print_result "INFO" "数字字符要求" "设置: $dcredit"
        fi
        
        local ucredit=$(grep "^ucredit" /etc/security/pwquality.conf | awk '{print $3}' || echo "unknown")
        if [ "$ucredit" != "unknown" ]; then
            print_result "INFO" "大写字母要求" "设置: $ucredit"
        fi
    else
        print_result "WARN" "密码质量配置文件不存在" "建议安装libpam-pwquality并配置密码策略"
    fi
    
    # 检查PAM密码配置（Debian/Ubuntu系统）
    if [ -f "/etc/pam.d/common-password" ]; then
        if grep -q "pam_pwquality.so" /etc/pam.d/common-password; then
            print_result "PASS" "PAM密码质量模块已配置" "Debian/Ubuntu系统密码策略已启用"
        else
            print_result "WARN" "PAM密码质量模块未找到" "建议在common-password中配置pam_pwquality.so"
        fi
    # 检查PAM密码配置（RHEL/CentOS系统）
    elif [ -f "/etc/pam.d/system-auth" ]; then
        if grep -q "pam_pwquality.so" /etc/pam.d/system-auth; then
            print_result "PASS" "PAM密码质量模块已配置" "RHEL/CentOS系统密码策略已启用"
        else
            print_result "WARN" "PAM密码质量模块未找到" "建议在system-auth中配置pam_pwquality.so"
        fi
    fi
    
    # 检查密码历史记录设置
    if [ -f "/etc/pam.d/common-password" ] || [ -f "/etc/pam.d/system-auth" ]; then
        if grep -q "remember=" /etc/pam.d/common-password /etc/pam.d/system-auth 2>/dev/null; then
            local remember=$(grep "remember=" /etc/pam.d/common-password /etc/pam.d/system-auth 2>/dev/null | head -1 | sed 's/.*remember=\([0-9]*\).*/\1/')
            print_result "PASS" "密码历史记录已配置" "记住最近 $remember 个密码"
        else
            print_result "WARN" "未配置密码历史记录" "建议配置remember参数防止密码重用"
        fi
    fi
}

# ============================================
# Sudo权限配置检查函数
# Function to check sudo privilege configuration
# ============================================
# 功能说明 (Function description):
#   检查sudo权限管理的配置和安全设置，确保特权提升机制安全可控
#   Check sudo privilege management configuration and security settings to ensure privilege escalation is secure and controllable
# 检查项目 (Check items):
#   - sudoers文件语法正确性检查 (sudoers file syntax correctness check)
#   - sudo操作日志记录配置 (sudo operation logging configuration)
#   - 安全选项设置验证 (security options settings verification)
#   - 环境变量和超时配置 (environment variables and timeout configuration)
#   - TTY要求和权限分配 (TTY requirements and privilege allocation)
# Sudo安全原则 (Sudo security principles):
#   - 最小权限原则：仅授予必要权限 (Principle of least privilege: grant only necessary permissions)
#   - 审计追踪：记录所有sudo操作 (Audit trail: log all sudo operations)
#   - 环境隔离：重置环境变量 (Environment isolation: reset environment variables)
#   - 会话管理：合理设置超时时间 (Session management: reasonable timeout settings)
# 关键配置选项 (Key configuration options):
#   - logfile: 指定sudo操作日志文件 (Specify sudo operation log file)
#   - requiretty: 要求在真实终端执行 (Require execution in real terminal)
#   - env_reset: 重置环境变量提高安全性 (Reset environment variables for security)
#   - timestamp_timeout: 设置sudo会话超时 (Set sudo session timeout)
# 配置文件位置 (Configuration file locations):
#   - /etc/sudoers: 主配置文件 (Main configuration file)
#   - /etc/sudoers.d/: 附加配置目录 (Additional configuration directory)
# ============================================
check_sudo_config() {
    echo -e "\n${BLUE}=== Sudo权限配置检查 ===${NC}"
    
    # 检查sudoers文件语法正确性 (Check sudoers file syntax correctness)
    if visudo -c 2>/dev/null; then
        print_result "PASS" "sudoers文件语法正确" "配置文件格式有效"
    else
        print_result "FAIL" "sudoers文件存在语法错误" "请检查sudo配置文件语法"
    fi
    
    # 检查sudo操作日志配置
    if grep -q "Defaults.*logfile" /etc/sudoers /etc/sudoers.d/* 2>/dev/null; then
        local logfile=$(grep "Defaults.*logfile" /etc/sudoers /etc/sudoers.d/* 2>/dev/null | head -1 | sed 's/.*logfile=\([^[:space:]]*\).*/\1/')
        print_result "PASS" "sudo日志记录已配置" "日志文件: $logfile"
    else
        print_result "WARN" "sudo日志记录未配置" "建议配置logfile选项记录sudo操作"
    fi
    
    # 检查requiretty设置（要求TTY终端）
    if grep -q "Defaults.*requiretty" /etc/sudoers /etc/sudoers.d/* 2>/dev/null; then
        print_result "PASS" "sudo requiretty已配置" "要求在真实终端中执行sudo"
    else
        print_result "INFO" "sudo requiretty未配置" "允许在非TTY环境中使用sudo"
    fi
    
    # 检查环境变量重置设置
    if grep -q "Defaults.*env_reset" /etc/sudoers /etc/sudoers.d/* 2>/dev/null; then
        print_result "PASS" "sudo环境变量重置已配置" "提高sudo执行安全性"
    else
        print_result "WARN" "sudo环境变量重置未配置" "建议启用env_reset选项"
    fi
    
    # 检查sudo超时设置
    if grep -q "Defaults.*timestamp_timeout" /etc/sudoers /etc/sudoers.d/* 2>/dev/null; then
        local timeout=$(grep "Defaults.*timestamp_timeout" /etc/sudoers /etc/sudoers.d/* 2>/dev/null | head -1 | sed 's/.*timestamp_timeout=\([0-9]*\).*/\1/')
        print_result "INFO" "sudo超时设置" "超时时间: $timeout 分钟"
    fi
}

# ============================================
# 文件权限检查函数
# Function to check file permissions
# ============================================
# 功能说明 (Function description):
#   检查关键系统文件的权限设置，确保敏感文件不被未授权访问
#   Check critical system file permissions to ensure sensitive files are not accessed by unauthorized users
# 检查项目 (Check items):
#   - 关键系统文件权限验证 (Critical system file permissions verification)
#   - SSH配置文件权限检查 (SSH configuration file permissions check)
#   - sudo配置文件权限验证 (sudo configuration file permissions verification)
#   - 敏感目录权限检查 (Sensitive directory permissions check)
#   - 全局可写文件检测 (World-writable files detection)
# 权限安全原则 (Permission security principles):
#   - 最小权限原则：仅授予必要的访问权限 (Principle of least privilege: grant only necessary access)
#   - 权限分离：不同文件设置不同权限级别 (Permission separation: different permission levels for different files)
#   - 敏感文件保护：密码文件等仅root可读 (Sensitive file protection: password files readable only by root)
#   - 配置文件安全：防止未授权修改 (Configuration file security: prevent unauthorized modifications)
# 关键文件权限标准 (Critical file permission standards):
#   - /etc/passwd: 644 (用户账户信息，公开可读) (User account info, publicly readable)
#   - /etc/shadow: 640 (密码哈希，仅root和shadow组) (Password hashes, root and shadow group only)
#   - /etc/ssh/sshd_config: 600 (SSH配置，仅root) (SSH config, root only)
#   - /etc/sudoers: 440 (sudo配置，仅root读取) (sudo config, root read only)
# 目录权限标准 (Directory permission standards):
#   - /root: 700 (root主目录，仅root访问) (root home directory, root access only)
#   - /etc: 755 (系统配置目录，公开可读) (System config directory, publicly readable)
#   - /var/log: 755 (日志目录，公开可读) (Log directory, publicly readable)
# ============================================
check_file_permissions() {
    echo -e "\n${BLUE}=== 文件权限检查 ===${NC}"
    
    # 定义需要检查的关键系统文件及其期望权限 (Define critical system files and their expected permissions)
    local files_to_check=(
        "/etc/passwd:644:用户账户信息文件"
        "/etc/shadow:640:用户密码哈希文件"
        "/etc/group:644:用户组信息文件"
        "/etc/gshadow:640:用户组密码文件"
        "/etc/ssh/sshd_config:600:SSH服务配置文件"
        "/etc/sudoers:440:sudo权限配置文件"
    )
    
    # 逐个检查文件权限
    for file_perm in "${files_to_check[@]}"; do
        local file=$(echo "$file_perm" | cut -d':' -f1)
        local expected_perm=$(echo "$file_perm" | cut -d':' -f2)
        local description=$(echo "$file_perm" | cut -d':' -f3)
        
        if [ -f "$file" ]; then
            local actual_perm=$(stat -c "%a" "$file" 2>/dev/null)
            if [ "$actual_perm" = "$expected_perm" ] || [ "$actual_perm" -le "$expected_perm" ]; then
                print_result "PASS" "$description权限正确" "文件: $file，权限: $actual_perm"
            else
                print_result "WARN" "$description权限过宽" "文件: $file，当前: $actual_perm，期望: $expected_perm 或更严格"
            fi
        else
            print_result "WARN" "文件不存在" "$description: $file"
        fi
    done
    
    # 检查/etc目录下的全局可写文件
    local world_writable=$(find /etc -type f -perm -002 2>/dev/null | wc -l)
    if [ $world_writable -eq 0 ]; then
        print_result "PASS" "/etc目录无全局可写文件" "系统配置文件权限安全"
    else
        print_result "WARN" "/etc目录存在全局可写文件" "发现 $world_writable 个文件，存在安全风险"
    fi
    
    # 检查重要目录权限
    local important_dirs=(
        "/root:700:root用户主目录"
        "/etc:755:系统配置目录"
        "/var/log:755:系统日志目录"
    )
    
    for dir_perm in "${important_dirs[@]}"; do
        local dir=$(echo "$dir_perm" | cut -d':' -f1)
        local expected_perm=$(echo "$dir_perm" | cut -d':' -f2)
        local description=$(echo "$dir_perm" | cut -d':' -f3)
        
        if [ -d "$dir" ]; then
            local actual_perm=$(stat -c "%a" "$dir" 2>/dev/null)
            if [ "$actual_perm" = "$expected_perm" ] || [ "$actual_perm" -le "$expected_perm" ]; then
                print_result "PASS" "$description权限正确" "目录: $dir，权限: $actual_perm"
            else
                print_result "WARN" "$description权限过宽" "目录: $dir，当前: $actual_perm，期望: $expected_perm 或更严格"
            fi
        fi
    done
}

# ============================================
# 内核安全参数检查函数
# Function to check kernel security parameters
# ============================================
# 功能说明 (Function description):
#   验证关键的内核安全参数设置，确保系统网络安全和内核安全防护
#   Verify critical kernel security parameter settings to ensure system network security and kernel security protection
# 检查项目 (Check items):
#   - IP转发设置防护 (IP forwarding protection settings)
#   - ICMP重定向攻击防护 (ICMP redirect attack protection)
#   - 源路由攻击防护 (Source routing attack protection)
#   - Martian包异常检测 (Martian packet anomaly detection)
#   - ICMP广播攻击防护 (ICMP broadcast attack protection)
#   - TCP SYN洪水攻击防护 (TCP SYN flood attack protection)
#   - 内核信息访问控制 (Kernel information access control)
# 网络安全参数说明 (Network security parameters description):
#   - net.ipv4.ip_forward: 控制IP包转发功能 (Control IP packet forwarding)
#   - net.ipv4.conf.all.send_redirects: 控制发送ICMP重定向 (Control sending ICMP redirects)
#   - net.ipv4.conf.all.accept_redirects: 控制接受ICMP重定向 (Control accepting ICMP redirects)
#   - net.ipv4.conf.all.accept_source_route: 控制源路由包处理 (Control source route packet handling)
#   - net.ipv4.conf.all.log_martians: 记录异常源地址包 (Log packets with abnormal source addresses)
#   - net.ipv4.icmp_echo_ignore_broadcasts: 忽略ICMP广播 (Ignore ICMP broadcasts)
#   - net.ipv4.tcp_syncookies: 启用SYN Cookies防护 (Enable SYN Cookies protection)
# 系统安全参数说明 (System security parameters description):
#   - kernel.dmesg_restrict: 限制dmesg访问防止信息泄露 (Restrict dmesg access to prevent information disclosure)
# 安全威胁防护 (Security threat protection):
#   - 路由攻击：防止系统被用作非法路由器 (Routing attacks: prevent system being used as illegal router)
#   - 重定向攻击：防止网络流量被恶意重定向 (Redirect attacks: prevent malicious traffic redirection)
#   - Smurf攻击：防止ICMP广播放大攻击 (Smurf attacks: prevent ICMP broadcast amplification)
#   - SYN洪水：防止TCP连接耗尽攻击 (SYN flood: prevent TCP connection exhaustion)
# ============================================
check_kernel_parameters() {
    echo -e "\n${BLUE}=== 内核安全参数检查 ===${NC}"
    
    # 定义需要检查的内核参数及其期望值 (Define kernel parameters to check and their expected values)
    # 格式：参数名:期望值 (Format: parameter_name:expected_value)
    local params_to_check=(
        "net.ipv4.ip_forward:0"                    # 禁用IP转发，防止系统被用作路由器
        "net.ipv4.conf.all.send_redirects:0"       # 禁用发送ICMP重定向
        "net.ipv4.conf.all.accept_redirects:0"     # 禁用接受ICMP重定向
        "net.ipv4.conf.all.accept_source_route:0"  # 禁用源路由包
        "net.ipv4.conf.all.log_martians:1"         # 启用记录Martian包（异常源地址包）
        "net.ipv4.icmp_echo_ignore_broadcasts:1"   # 忽略ICMP广播请求，防止Smurf攻击
        "net.ipv4.tcp_syncookies:1"                # 启用TCP SYN Cookies，防止SYN洪水攻击
        "kernel.dmesg_restrict:1"                  # 限制非特权用户访问dmesg
    )
    
    # 逐个检查内核参数配置
    for param_value in "${params_to_check[@]}"; do
        local param=$(echo "$param_value" | cut -d':' -f1)      # 提取参数名
        local expected=$(echo "$param_value" | cut -d':' -f2)   # 提取期望值
        
        # 获取当前参数值
        local actual=$(sysctl -n "$param" 2>/dev/null || echo "unknown")
        
        # 比较实际值与期望值
        if [ "$actual" = "$expected" ]; then
            print_result "PASS" "内核参数配置正确" "$param = $actual"
        elif [ "$actual" = "unknown" ]; then
            print_result "WARN" "内核参数未找到" "参数: $param，可能系统不支持此参数"
        else
            print_result "WARN" "内核参数配置不当" "$param = $actual（期望值: $expected）"
        fi
    done
}

# ============================================
# 安全软件包检查函数
# ============================================
# 功能说明：检查系统中推荐的安全工具和不安全的软件包
# 检查项目：
#   - 推荐安全工具：AIDE（文件完整性检查）、rkhunter（rootkit检测）、
#     chkrootkit（rootkit扫描）、lynis（安全审计）、clamav（防病毒）
#   - 不安全软件包：telnet、rsh、rcp、tftp等明文传输工具
#   - 软件包安装状态和版本信息
# 安全原则：
#   - 安装必要的安全监控工具进行持续防护
#   - 移除不安全的网络服务避免安全风险
#   - 定期更新安全工具保持最新防护能力
#   - 使用加密替代方案（SSH替代telnet，SCP替代rcp）
# 工具说明：
#   - AIDE：高级入侵检测环境，监控文件系统变化
#   - rkhunter：检测rootkit、后门和本地漏洞
#   - chkrootkit：检查系统中的rootkit痕迹
#   - lynis：安全审计工具，全面评估系统安全
#   - clamav：开源防病毒引擎
check_security_packages() {
    echo -e "\n${BLUE}=== 安全软件包检查 ===${NC}"
    
    # 定义推荐安装的安全软件包
    local security_packages=("aide" "rkhunter" "chkrootkit" "lynis" "clamav")
    
    # 检查推荐的安全软件包安装情况
    for package in "${security_packages[@]}"; do
        # 检查软件包是否已安装（支持多种包管理器）
        if command -v "$package" >/dev/null 2>&1 || dpkg -l "$package" >/dev/null 2>&1 || rpm -q "$package" >/dev/null 2>&1; then
            print_result "PASS" "安全软件包已安装" "软件包: $package"
        else
            print_result "INFO" "安全软件包未安装" "建议安装: $package"
        fi
    done
    
    # 检查不安全的软件包（应该被移除）
    local unwanted_packages=("telnet" "rsh-server" "rsh" "ypbind" "ypserv" "tftp" "tftp-server")
    
    # 检查不安全软件包的安装情况
    for package in "${unwanted_packages[@]}"; do
        # 检查不安全软件包是否存在
        if command -v "$package" >/dev/null 2>&1 || dpkg -l "$package" >/dev/null 2>&1 || rpm -q "$package" >/dev/null 2>&1; then
            print_result "WARN" "发现不安全软件包" "软件包: $package，建议卸载"
        else
            print_result "PASS" "不安全软件包未安装" "软件包: $package"
        fi
    done
}

# ============================================
# 安全验证结果汇总函数
# ============================================
# 功能说明：计算并显示整体安全评分和检查结果统计
# 统计项目：
#   - 通过检查数量（PASSED）- 符合安全标准的配置项
#   - 失败检查数量（FAILED）- 存在安全风险的配置项
#   - 警告检查数量（WARNING）- 需要关注的潜在问题
#   - 总体安全评分（百分比）- 基于通过率计算
# 评分标准：
#   - 95-100%：优秀安全状态，系统安全配置完善
#   - 80-94%：良好安全状态，基本符合安全要求
#   - 70-79%：一般安全状态，存在一些安全隐患
#   - <70%：安全状态较差，需要立即改进
# 输出格式：
#   - 彩色文本显示，便于快速识别问题严重程度
#   - 提供具体的改进建议和优先级指导
#   - 包含详细的统计信息和安全评估
display_summary() {
    echo -e "\n${BLUE}=== 安全验证结果汇总 ===${NC}"
    
    # 显示检查统计信息
    echo -e "检查项目总数: $TOTAL_CHECKS"
    echo -e "${GREEN}通过检查: $PASSED_CHECKS${NC}"
    echo -e "${RED}失败检查: $FAILED_CHECKS${NC}"
    echo -e "${YELLOW}警告检查: $WARNING_CHECKS${NC}"
    
    # 计算安全评分（基于通过率）
    local score=0
    if [ $TOTAL_CHECKS -gt 0 ]; then
        score=$((PASSED_CHECKS * 100 / TOTAL_CHECKS))
    fi
    echo -e "\n安全评分: $score%"
    
    # 根据检查结果给出总体评估
    if [ $FAILED_CHECKS -eq 0 ] && [ $WARNING_CHECKS -eq 0 ]; then
        echo -e "${GREEN}✓ 优秀！所有安全检查均已通过。${NC}"
    elif [ $FAILED_CHECKS -eq 0 ]; then
        echo -e "${YELLOW}⚠ 良好！无失败项目，但有一些警告需要处理。${NC}"
    else
        echo -e "${RED}✗ 发现安全问题！请处理失败的检查项目。${NC}"
    fi
    
    # 提供改进建议
    echo -e "\n${BLUE}改进建议：${NC}"
    if [ $FAILED_CHECKS -gt 0 ]; then
        echo -e "${RED}→${NC} 优先处理 $FAILED_CHECKS 个失败项目，这些是严重的安全风险"
    fi
    if [ $WARNING_CHECKS -gt 0 ]; then
        echo -e "${YELLOW}→${NC} 关注 $WARNING_CHECKS 个警告项目，进一步提升安全性"
    fi
    if [ $score -lt 80 ]; then
        echo -e "${RED}→${NC} 安全评分较低，建议全面检查和加固系统安全配置"
    elif [ $score -lt 95 ]; then
        echo -e "${YELLOW}→${NC} 安全配置基本良好，建议处理剩余问题以达到更高安全标准"
    fi
}

# ============================================================================
# 主程序执行部分
# ============================================================================

# 显示脚本标题和启动信息
echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                    系统安全验证脚本                        ║${NC}"
echo -e "${BLUE}║                     $(date '+%Y-%m-%d %H:%M:%S')                     ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"

echo -e "\n${BLUE}开始执行系统安全检查...${NC}"
echo -e "${BLUE}本脚本将检查以下安全配置项目：${NC}"
echo -e "  • SSH服务配置安全性"
echo -e "  • 防火墙配置状态"
echo -e "  • SELinux安全策略"
echo -e "  • 审计系统配置"
echo -e "  • Fail2Ban入侵防护"
echo -e "  • 密码策略设置"
echo -e "  • Sudo权限配置"
echo -e "  • 关键文件权限"
echo -e "  • 内核安全参数"
echo -e "  • 安全软件包状态"

# 执行所有安全检查函数
# 按照从基础到高级的顺序进行检查
check_ssh_config          # 1. SSH服务配置检查
check_firewall_config     # 2. 防火墙配置检查
check_selinux_config      # 3. SELinux配置检查
check_audit_config        # 4. 审计系统检查
check_fail2ban_config     # 5. Fail2Ban配置检查
check_password_policy     # 6. 密码策略检查
check_sudo_config         # 7. Sudo配置检查
check_file_permissions    # 8. 文件权限检查
check_kernel_parameters   # 9. 内核参数检查
check_security_packages   # 10. 安全软件包检查

# 显示检查结果汇总
display_summary

# 根据检查结果设置退出代码
# 退出代码说明：
#   0 - 所有检查通过，无警告
#   1 - 存在失败的检查项目（严重安全问题）
#   2 - 无失败项目，但存在警告（需要关注的安全问题）
if [ $FAILED_CHECKS -gt 0 ]; then
    echo -e "\n${RED}脚本执行完成，发现 $FAILED_CHECKS 个严重安全问题！${NC}"
    exit 1
elif [ $WARNING_CHECKS -gt 0 ]; then
    echo -e "\n${YELLOW}脚本执行完成，发现 $WARNING_CHECKS 个需要关注的安全问题。${NC}"
    exit 2
else
    echo -e "\n${GREEN}脚本执行完成，所有安全检查均通过！${NC}"
    exit 0
fi